package com.erlang.spring.dao.impl;

import com.erlang.spring.dao.AccountDao;
import com.erlang.spring.mapper.AccountMapper;
import com.erlang.spring.pojo.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Description：账户dao接口,实现类
 */
@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {

  @Autowired
  private JdbcTemplate jdbcTemplate;

  @Override
  public int saveAccount(Account account) {
    String sql = "INSERT INTO `jt_account` ( `account_name`, `money`) VALUES ( ?, ?)";
    return jdbcTemplate.update(sql, account.getAccountName(),account.getMoney());
  }

  @Override
  public int deleteAccountById(int id) {
    String sql = "delete from `jt_account` where id =?";
    return jdbcTemplate.update(sql,id);
  }

  @Override
  public int updateAccountById(Account account) {
    String sql = "update jt_account set account_name=?,money=? where id = ?";
    return jdbcTemplate.update(sql, account.getAccountName(),account.getMoney(),account.getId());
  }

  @Override
  public Account findAccountById(int id) {
    String sql = "select * from jt_account where id =?";
    return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Account.class),id);
  }

  @Override
  public List<Account> findAll() {
    String sql = "select * from jt_account";
    return jdbcTemplate.query(sql, new AccountMapper());
  }

  @Override
  public Integer countAccount() {
    String sql = "select count(1) from jt_account";
    return jdbcTemplate.queryForObject(sql, Integer.class);
  }
}